<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>SignalR 聊天测试</title>
    <style>
        body {
            font-family: 'Microsoft YaHei', Arial, sans-serif;
            margin: 0;
            padding: 20px;
            background-color: #f5f5f5;
        }
        .container {
            max-width: 800px;
            margin: 0 auto;
            background-color: white;
            border-radius: 8px;
            box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
            padding: 20px;
        }
        h1 {
            color: #333;
            text-align: center;
            margin-bottom: 20px;
        }
        .connection-status {
            padding: 10px;
            margin-bottom: 20px;
            border-radius: 4px;
            text-align: center;
        }
        .connected {
            background-color: #d4edda;
            color: #155724;
        }
        .disconnected {
            background-color: #f8d7da;
            color: #721c24;
        }
        .form-group {
            margin-bottom: 15px;
        }
        label {
            display: block;
            margin-bottom: 5px;
            font-weight: bold;
        }
        input[type="text"], textarea {
            width: 100%;
            padding: 8px;
            border: 1px solid #ddd;
            border-radius: 4px;
            box-sizing: border-box;
        }
        button {
            background-color: #007bff;
            color: white;
            border: none;
            padding: 10px 15px;
            border-radius: 4px;
            cursor: pointer;
            font-size: 14px;
        }
        button:hover {
            background-color: #0069d9;
        }
        .chat-container {
            display: flex;
            margin-top: 20px;
        }
        .user-list {
            width: 30%;
            border-right: 1px solid #ddd;
            padding-right: 15px;
        }
        .chat-box {
            width: 70%;
            padding-left: 15px;
        }
        .messages {
            height: 300px;
            border: 1px solid #ddd;
            border-radius: 4px;
            padding: 10px;
            overflow-y: auto;
            margin-bottom: 15px;
            background-color: #f9f9f9;
        }
        .message {
            margin-bottom: 10px;
            padding: 8px;
            border-radius: 4px;
        }
        .sent {
            background-color: #e3f2fd;
            margin-left: 20%;
            text-align: right;
        }
        .received {
            background-color: #f1f1f1;
            margin-right: 20%;
        }
        .user-item {
            padding: 8px;
            margin-bottom: 5px;
            border-radius: 4px;
            cursor: pointer;
        }
        .user-item:hover {
            background-color: #f1f1f1;
        }
        .user-item.active {
            background-color: #e3f2fd;
        }
        .time {
            font-size: 12px;
            color: #777;
        }
        .log {
            margin-top: 20px;
            padding: 10px;
            background-color: #f8f9fa;
            border: 1px solid #ddd;
            border-radius: 4px;
            height: 100px;
            overflow-y: auto;
        }
    </style>
</head>
<body>
    <div class="container">
        <h1>SignalR 聊天测试</h1>
        
        <div id="connectionStatus" class="connection-status disconnected">
            未连接
        </div>
        
        <div class="form-group">
            <label for="userId">用户 ID</label>
            <input type="text" id="userId" placeholder="输入您的用户ID">
        </div>
        
        <div class="form-group">
            <button id="connectButton">连接</button>
            <button id="disconnectButton" disabled>断开连接</button>
        </div>
        
        <div class="chat-container">
            <div class="user-list">
                <h3>用户列表</h3>
                <div class="form-group">
                    <input type="text" id="receiverId" placeholder="输入接收者ID">
                    <button id="addUserButton">添加用户</button>
                </div>
                <div id="usersList"></div>
            </div>
            
            <div class="chat-box">
                <h3>聊天框</h3>
                <div id="messages" class="messages"></div>
                
                <div class="form-group">
                    <textarea id="messageInput" placeholder="输入消息..." rows="3"></textarea>
                </div>
                
                <div class="form-group">
                    <button id="sendButton" disabled>发送</button>
                </div>
            </div>
        </div>
        
        <div class="log">
            <h3>日志</h3>
            <div id="logMessages"></div>
        </div>
    </div>
    
    <script src="https://cdn.jsdelivr.net/npm/@microsoft/signalr@6.0.0/dist/browser/signalr.min.js"></script>
    <script>
        document.addEventListener('DOMContentLoaded', function() {
            const connectionStatus = document.getElementById('connectionStatus');
            const connectButton = document.getElementById('connectButton');
            const disconnectButton = document.getElementById('disconnectButton');
            const sendButton = document.getElementById('sendButton');
            const userIdInput = document.getElementById('userId');
            const receiverIdInput = document.getElementById('receiverId');
            const messageInput = document.getElementById('messageInput');
            const messagesContainer = document.getElementById('messages');
            const usersListContainer = document.getElementById('usersList');
            const addUserButton = document.getElementById('addUserButton');
            const logMessages = document.getElementById('logMessages');
            
            let connection = null;
            let activeReceiverId = null;
            
            // 记录日志
            function log(message) {
                const logItem = document.createElement('div');
                logItem.textContent = `${new Date().toLocaleTimeString()}: ${message}`;
                logMessages.appendChild(logItem);
                logMessages.scrollTop = logMessages.scrollHeight;
            }
            
            // 添加消息到聊天框
            function addMessage(message, isSent) {
                const messageElement = document.createElement('div');
                messageElement.classList.add('message');
                messageElement.classList.add(isSent ? 'sent' : 'received');
                
                const timeElement = document.createElement('div');
                timeElement.classList.add('time');
                timeElement.textContent = new Date().toLocaleTimeString();
                
                const contentElement = document.createElement('div');
                contentElement.textContent = message;
                
                messageElement.appendChild(contentElement);
                messageElement.appendChild(timeElement);
                
                messagesContainer.appendChild(messageElement);
                messagesContainer.scrollTop = messagesContainer.scrollHeight;
            }
            
            // 添加用户到列表
            function addUserToList(userId) {
                // 检查是否已存在
                const existingUser = document.querySelector(`.user-item[data-user-id="${userId}"]`);
                if (existingUser) {
                    return;
                }
                
                const userItem = document.createElement('div');
                userItem.classList.add('user-item');
                userItem.setAttribute('data-user-id', userId);
                userItem.textContent = userId;
                
                userItem.addEventListener('click', function() {
                    // 移除其他用户的活动状态
                    document.querySelectorAll('.user-item').forEach(item => {
                        item.classList.remove('active');
                    });
                    
                    // 设置当前用户为活动状态
                    userItem.classList.add('active');
                    activeReceiverId = userId;
                    log(`已选择与用户 ${userId} 聊天`);
                });
                
                usersListContainer.appendChild(userItem);
            }
            
            // 连接到 SignalR Hub
            connectButton.addEventListener('click', function() {
                const userId = userIdInput.value.trim();
                if (!userId) {
                    alert('请输入用户ID');
                    return;
                }
                
                // 创建连接
                connection = new signalR.HubConnectionBuilder()
                    .withUrl(`/api/chathub?userId=${userId}`)
                    .withAutomaticReconnect()
                    .build();
                
                // 连接成功事件
                connection.on('Connected', function(data) {
                    connectionStatus.textContent = `已连接，连接ID: ${data.connectionId}`;
                    connectionStatus.classList.remove('disconnected');
                    connectionStatus.classList.add('connected');
                    
                    connectButton.disabled = true;
                    disconnectButton.disabled = false;
                    sendButton.disabled = false;
                    
                    log(`连接成功，用户ID: ${userId}, 连接ID: ${data.connectionId}`);
                });
                
                // 接收私聊消息
                connection.on('ReceivePrivateMessage', function(data) {
                    log(`收到来自 ${data.senderName || data.senderId} 的消息`);
                    addMessage(`${data.senderName || data.senderId}: ${data.message}`, false);
                    
                    // 确保发送者在用户列表中
                    addUserToList(data.senderId);
                });
                
                // 接收聊天历史
                connection.on('ReceiveChatHistory', function(messages) {
                    log(`收到聊天历史记录，共 ${messages.length} 条消息`);
                    
                    // 清空当前消息
                    messagesContainer.innerHTML = '';
                    
                    // 显示历史消息
                    messages.forEach(msg => {
                        const isSent = msg.sender === userId;
                        addMessage(`${isSent ? '我' : msg.contactName}: ${msg.chatMessage}`, isSent);
                    });
                });
                
                // 错误处理
                connection.on('Error', function(data) {
                    log(`错误: ${data.message}`);
                    alert(`错误: ${data.message}`);
                });
                
                // 测试响应
                connection.on('TestResponse', function(message) {
                    log(`测试响应: ${message}`);
                });
                
                // 开始连接
                connection.start()
                    .then(function() {
                        log('连接已启动');
                        
                        // 发送测试连接请求
                        connection.invoke('TestConnection', '测试连接')
                            .catch(function(err) {
                                log(`测试连接失败: ${err}`);
                            });
                    })
                    .catch(function(err) {
                        log(`连接失败: ${err}`);
                        connectionStatus.textContent = `连接失败: ${err}`;
                    });
            });
            
            // 断开连接
            disconnectButton.addEventListener('click', function() {
                if (connection) {
                    connection.stop()
                        .then(function() {
                            connectionStatus.textContent = '未连接';
                            connectionStatus.classList.remove('connected');
                            connectionStatus.classList.add('disconnected');
                            
                            connectButton.disabled = false;
                            disconnectButton.disabled = true;
                            sendButton.disabled = true;
                            
                            log('已断开连接');
                        })
                        .catch(function(err) {
                            log(`断开连接失败: ${err}`);
                        });
                }
            });
            
            // 添加用户
            addUserButton.addEventListener('click', function() {
                const receiverId = receiverIdInput.value.trim();
                if (receiverId) {
                    addUserToList(receiverId);
                    receiverIdInput.value = '';
                    log(`添加用户 ${receiverId} 到列表`);
                }
            });
            
            // 发送消息
            sendButton.addEventListener('click', function() {
                if (!connection || !activeReceiverId) {
                    alert('请先连接并选择接收者');
                    return;
                }
                
                const message = messageInput.value.trim();
                if (!message) {
                    alert('请输入消息');
                    return;
                }
                
                connection.invoke('SendPrivateMessage', activeReceiverId, message)
                    .then(function() {
                        addMessage(`我: ${message}`, true);
                        messageInput.value = '';
                        log(`消息已发送给 ${activeReceiverId}`);
                    })
                    .catch(function(err) {
                        log(`发送消息失败: ${err}`);
                        alert(`发送消息失败: ${err}`);
                    });
            });
            
            // 按Enter键发送消息
            messageInput.addEventListener('keypress', function(e) {
                if (e.key === 'Enter' && !e.shiftKey) {
                    e.preventDefault();
                    sendButton.click();
                }
            });
        });
    </script>
</body>
</html> 